package cn.online.zhuanshenben.service;

import cn.online.zhuanshenben.dao.SuserMapper;
import cn.online.zhuanshenben.entity.Suser;
import cn.online.zhuanshenben.entity.SuserExample;
import cn.online.zhuanshenben.util.MybatisUtil;
import cn.online.zhuanshenben.util.StrUtil;
import cn.online.zhuanshenben.vo.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
public class SuserService {
    public static final SuserService ME = new SuserService();

    public int add(Suser user) {
        SqlSession session = MybatisUtil.get();
        try {
            SuserMapper mapper = session.getMapper(SuserMapper.class);
            return mapper.insertSelective(user);
        } finally {
            MybatisUtil.close(session);
        }
    }

    public Page<Suser> search(String phone, String sname, String school, String major, int page, int size) {

        SqlSession session = MybatisUtil.get();
        com.github.pagehelper.Page<Suser> p = PageHelper.startPage(page, size);

        SuserMapper mapper = session.getMapper(SuserMapper.class);
        SuserExample user = new SuserExample();
        SuserExample.Criteria criteria = user.createCriteria();
        if (!StrUtil.isBlank(sname))
            criteria.andSnameLike("%" + sname + "%");

        if (!StrUtil.isBlank(phone))
            criteria.andPhoneLike("%" + phone + "%");
        if (!StrUtil.isBlank(school))
            criteria.andSchoolLike("%" + school + "%");
        if (!StrUtil.isBlank(major))
            criteria.andMajorLike("%" + major + "%");

        List<Suser> susers = mapper.selectByExample(user);

        MybatisUtil.close(session);
        //long total = mapper.countByExample(user);
        //return new Page<Suser>(p.getTotal(),susers);
        return new Page<Suser>(p.getTotal(), page, size, susers);
    }

    public static void main(String[] args) {
        SuserService suserService = new SuserService();
        Page<Suser> search = suserService.search("135", "市", null, null, 2, 10);
        search.getData().forEach(x -> {
            System.out.println(x);
            System.out.println(">>>>>>>>>>>>>>>>>>>>");
        });
    }

    public Suser get(Long id) {
        SqlSession session = MybatisUtil.get();
        try {
            SuserMapper mapper = session.getMapper(SuserMapper.class);
            return mapper.selectByPrimaryKey(id);
        } finally {
            MybatisUtil.close(session);
        }
    }

    public int batDel(long[] id) {
        SqlSession session = MybatisUtil.get();
        int d=0;
        try {
            SuserMapper mapper = session.getMapper(SuserMapper.class);
            for (long i:id)
                d+=mapper.deleteByPrimaryKey(i);
        } finally {
            MybatisUtil.close(session);
        }
        return d;
    }
}
